import com.sun.xml.internal.ws.resources.ClientMessages;

import javax.security.sasl.SaslClient;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-11-02
 * Time: 20:15
 */
public class TcpEchoClient {
    public Socket client;
    //TCP中客户端构造函数的ip和port指的是要链接的服务器的IP和port
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        this.client = new Socket(serverIp, serverPort);
    }

    public void start() throws IOException {
        System.out.println("和服务器建立链接成功");
        Scanner scanner = new Scanner(System.in);
        //这里针对TCP的读写和对于文件的读写是一摸一样的
        //利用socket构造文件流
        try (InputStream inputStream = client.getInputStream()) {
            try (OutputStream outputStream = client.getOutputStream()) {
                //接收从控制台输入的字符串
                while (true) {
                    System.out.println("->");
                    String request = scanner.next();
                    //构造请求并发送请求(PrintWriter和Scanner对应)//注意文件流
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();//如果不及时刷新,服务器可能不能及时接收到数据
                    //接收响应
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    //显示到控制台上
                    System.out.printf("[req:%s  resp:%s]\n", request, response);
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}